const app = getApp()
const search = require('../../lib/search.js');
const sr = new search.Search();
var rule={};
var keywords='';
var skip=0;
var tx_=0;

Page({
    data: {
        password: null,
        card: null,
        menu: false,
        path: {},
        x: 0,
        y: 0,
        ex: 0,
        ey: 0,
        t: false,
        show: false
    },
    onLoad: function (res) {
        wx.setNavigationBarColor({
            frontColor: '#ffffff',
            backgroundColor: '#333333'
        })
        const that = this;
        const file = require('../../lib/file.js');
        const dl = new file.file();
        dl.loadFont();
        dl.fill(function () {
            that.setData({
                path: dl.all
            })
        });
        
        const password = parseInt(res.password);
        this.setData({
            password: password
        });
        const db = wx.cloud.database();
        db.collection("card").doc(password).get({
            success(res) {
                that.addToData(res.data);
            }
        })

        const rl=new search.Rule({});
        var parse = rl.unzip(res);
        rule = parse.rule;
        keywords = parse.keywords;
        skip=parse.skip;
        console.log(res,skip,rule)
    },
    onPullDownRefresh: function () {
        wx.stopPullDownRefresh();
    },
    uploadPic: function () {
        var picName = 'public/' + this.data.password + ".jpg";
        wx.chooseImage({
            success: chooseResult => {
                wx.cloud.uploadFile({
                    cloudPath: picName,
                    filePath: chooseResult.tempFilePaths[0],
                    success: res => {
                        wx.showToast({
                            title: '上传成功',
                        });
                    },
                })
            },
        })
    },
    changePicSrc: function (res) {
        var that = this;
        if (this.data.src == "public") {
            wx.showModal({
                title: '卡图缺失啦！',
                content: '帮我们上传卡图，能让我们的查卡器做的更好！',
                confirmText: '好的！',
                cancelText: "没时间！",
                success(res) {
                    if (res.confirm) {
                        that.uploadPic();
                    }
                }
            })
        }
        this.setData({
            src: "public"
        })
    },
    onShareAppMessage: function (res) {
        var url = "https://6361-cards-2c53b0-1258076431.tcb.qcloud.la/pic/" + this.data.card.ifm._id + ".jpg";
        console.log(url);
        var share = {
            title: this.data.card.ifm.name,
            path: '/pages/cardIfm/cardIfm?password=' + this.data.card.ifm._id,
            imageUrl: url,
            success: function (res) {
                console.log("分享成功")
            },
            fail: function (res) {
                console.log("分享失败")
            }
        };
        console.log(share.imageUrl)
        return share;
    },
    addToDesk(e, side_ = false) {
        let card = {
            password: this.data.password,
            name: this.data.card.ifm.name,
            attack: this.data.card.ifm.attack ? this.data.card.ifm.attack : -9,
            level: this.data.card.ifm.level ? this.data.card.ifm.level : -9,
            type: this.data.card.ifm.type,
            type2: this.data.card.ifm.type2,
            type3: this.data.card.ifm.type3
        }
        const Desk = require("../../lib/cardDesk.js");
        if (app.globalData.desks.length > 0) {
            app.globalData.desks[0].add(card, side_);
        }
        else {
            const openid = app.globalData.openid;
            let desk = new Desk.Desk(openid);
            app.globalData.desks.unshift(desk);
            app.globalData.desks[0].add(card, side_);
        }
        wx.hideLoading();
    },
    addSide(e) {
        let side_ = true;
        this.addToDesk(e, side_)
    },
    addToData(card) {
        const Card = require("../../lib/card.js");
        const file = require("../../lib/file.js");
        const that = this;
        let r = this.getScale();
        this.setData({
            card: new Card.Card(card, 1.3 * r,false,false)
        })
        setTimeout(function () {
            let card1 = that.data.card;
            card1.animation = true;
            that.setData({
                card: card1
            })
        }, 100)
        setTimeout(function () {
            let card2 = that.data.card;
            card2.size = card2.size / 1.3;
            card2.opacity = 1;
            that.setData({
                card: card2,
                show: true
            })
        }, 150)
        let name = this.data.card.ifm.name;
        wx.setNavigationBarTitle({
            title: name,
        })
    },
    getScale() {
        let w = 0.8 * wx.getSystemInfoSync().windowWidth;
        let r = w / 600;
        this.setData({
            r:r
        });
        return r;
    },
    toggle() {
        const that = this;
        this.setData({
            menu: !that.data.menu
        })
        if (this.data.menu) {
            wx.setNavigationBarColor({
                frontColor: '#000000',
                backgroundColor: '#ffffff',
                animation: {
                    duration: 400,
                    timingFunc: 'easeOut'
                }
            })
        }
        else {
            wx.setNavigationBarColor({
                frontColor: '#ffffff',
                backgroundColor: '#333333',
                animation: {
                    duration: 400,
                    timingFunc: 'easeOut'
                }
            })
        }
    },
    toComment() {
        wx.navigateTo({
            url: '../comment/comment?id=' + this.data.card.ifm._id + "&type=card",
        })
    },
    rotate() {
        const that = this;
        this.setData({
            menu: false
        })
        wx.startDeviceMotionListening({
            interval: "ui",
            success() {
                wx.onDeviceMotionChange((e) => {
                    let x = -1*e.beta;
                    let y = 1.3 * e.gamma;
                    if (!that.data.t) {
                        var ex = x;
                        var ey = y;
                        setTimeout(function () {
                            that.setData({
                                t: true
                            })
                        },1000)
                    }
                    else if (that.data.t) {
                        var ex = x * 0.1 + that.data.ex * 0.9;
                        var ey = y * 0.1 + that.data.ey * 0.9;
                    }
                    let x_ = Math.abs(x - ex);
                    let y_ = Math.abs(y - ey);
                    let holo = ( x_ > y_ ? x_ : y_ ) / 20;
                    holo = holo > 1 ? 1 : holo;
                    that.setData({
                        x: (x - ex),
                        y: (y - ey),
                        ex: ex,
                        ey: ey,
                        holo: holo
                    })
                })
            }
        })
    },
    stopThat() {
        wx.stopDeviceMotionListening();
    },
    onHide() {
        this.stopThat();
        clearTimeout();
    },
    onUnload() {
        this.stopThat();
        clearTimeout();
    },
    onShow() {
        /*
        setTimeout(() => {
            this.rotate();
        },800)
        */
    },
    slide(num) {
        const that=this;
        const Card = require('../../lib/card.js');
        const r=this.getScale();
        this.setData({
            tx: 500 * num ,
            transition: 0,
            bg_t: false
        });
        wx.showNavigationBarLoading();
        console.log('送入迭代器的是：',keywords,rule,skip)
        sr.iter({
            keywords: keywords,
            rule: rule,
            num,
            skip: skip,
            success(res) {
                if (res.length>0) {
                    that.setData({
                        card: new Card.Card(res[0],r)
                    })
                    wx.setNavigationBarTitle({
                        title: res[0].name,
                    })
                }
                that.setData({
                    tx: 0,
                    transition: 0.5
                });
                wx.hideNavigationBarLoading();
            },
            fail() {
                that.setData({
                    tx: 0,
                    transition: 0.5
                });
                wx.hideNavigationBarLoading();
            }
        })
    },
    touchStart(e) {
        tx_ = e.changedTouches[0].clientX;
        this.setData({
            tx:0,
            transition: 0
        });
    },
    touchMove(e) {
        const that=this;
        this.setData({
            tx: e.changedTouches[0].clientX - tx_
        });
    },
    touchEnd(e) {
        const that = this;
        let x = e.changedTouches[0].clientX;
        if (x - tx_ > 50) {
            this.slide(-1);
        }
        else if (x - tx_ <= -50) {
            this.slide(1);
        }
        else {
            this.setData({
                tx: 0,
                transition: 0.5
            })
        }
    },
    bgLoaded() {
        this.setData({
            bg_t: true
        })
    },
    showMenu2() {
        const that=this;
        wx.showActionSheet({
            itemList: ['加入卡组', '加入副卡组','评论'],
            success(res) {
                if (res.tapIndex==0) {
                    that.addToDesk();
                }
                else if (res.tapIndex == 1) {
                    that.addSide();
                }
                else if (res.tapIndex == 2) {
                    that.toComment();
                }
            },
            fail(res) {
                console.log(res.errMsg)
            }
        })
    }
})
